﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Net;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Themn_DL_MasterPage2 : System.Web.UI.MasterPage
{
    PowerCreator.LMS.Web.DL.User.WebLearner opUser = new PowerCreator.LMS.Web.DL.User.WebLearner();
    PowerCreator.LMS.Web.Course.Course opCourse = new PowerCreator.LMS.Web.Course.Course();
    PowerCreator.LMS.Web.Course.Resource opResource = new PowerCreator.LMS.Web.Course.Resource();
    protected PowerCreator.LMS.Web.Config.WebConfig config = new PowerCreator.LMS.Web.Config.WebConfig();
    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    PowerCreator.LMS.ViewQuery.ViewQuery vq = new PowerCreator.LMS.ViewQuery.ViewQuery();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BinderUserLogin();
            rptClickResource();
            BinderWebClick();
            rptClickCourse();
        }
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            tb_login.Visible = true;
            tb_loginout.Visible = false;
        }
        else
        {
             PowerCreator.LMS.Web.DL.User.LoginEntity login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
             if (login.VOLearner == null)
             {
                 Session.Abandon();
                 PowerCreator.LMS.Common.Script.Script.ReloadMe();

             }
             else
             {
                 tb_login.Visible = false;
                 tb_loginout.Visible = true;
                 lbl_username.Text = login.UserName.Trim();
                 lbl_UserReal.Text = login.RealName.Trim();
             }
        }
        //btn_out.Text = config.GetLanagerValueByKey("SignOut", PowerCreator.LMS.Language.LanagetItemType.WebTitle);
    }
    protected void lnkbtn_EN_Click(object sender, EventArgs e)
    {
        Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_LANGEID] = "1";
    }
    protected void lnkbtn_CN_Click(object sender, EventArgs e)
    {
        Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_LANGEID] = "0";
    }
    protected void BinderUserLogin()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {

            //lal_UserLogin.Text = "<a  href=\"UserLogin.aspx\">登陆</a> |  <a  href=\"Register.aspx\">注册</a>";
            //btn_out.Visible = false;
        }
        else
        {
            login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            if (login == null)
            {
                //lal_UserLogin.Text = "<a  href=\"UserLogin.aspx\">登陆</a> |  <a  href=\"Register.aspx\">注册</a>";
                //btn_out.Visible = false;

            }
            else
            {
                //lal_UserLogin.Text = login.RealName.Trim() + ",欢迎光临大连市教师在线学习中心！| ";
                //btn_out.Visible = true;
            }
        }
    }
    protected void btn_out_Click(object sender, EventArgs e)
    {
        //PowerCreator.LMS.Web.User.User opUser = new PowerCreator.LMS.Web.User.User();
        //opUser.UpdateOnlineUserByUserID(GetLoginEntity.UserID);
        Session.Abandon();
        PowerCreator.LMS.Common.Script.Script.ReloadMe();
    }

    public void rptClickResource()//课件点击排行
    {
        string search = "";
        string orderBy = "ResourceClickNum desc";
        DataTable dt = opResource.QueryResource(search, orderBy, 9, 1);
        rptClkResource.DataSource = dt;
        rptClkResource.DataBind();

    }
    private void BinderWebClick()
    {
        //访问统计
        //今日在线
        PowerCreator.LMS.Web.DL.Project.TOLearner opLearner = new PowerCreator.LMS.Web.DL.Project.TOLearner();
        PowerCreator.LMS.Web.Course.Resource opResource = new PowerCreator.LMS.Web.Course.Resource();
        PowerCreator.LMS.Web.DL.User.WebLearner opWebLearner = new PowerCreator.LMS.Web.DL.User.WebLearner();
        PowerCreator.LMS.ViewQuery.ViewQuery obj = new PowerCreator.LMS.ViewQuery.ViewQuery();

        //PowerCreator.LMS.Web.User.User opUser = new PowerCreator.LMS.Web.User.User();
        string search = "";
        lbl_LearnerRegistorCount.Text = opLearner.Count(search).ToString();
        lbl_ResourceCount.Text = opResource.QueryResourceCount(search).ToString();
        search = " OnlineuserType=2";
        lbl_UserToDayHistoryOnline.Text = opWebLearner.QueryOnlineUserCount(search).ToString();
        lbl_UserToDayHistoryOnline02.Text = lbl_UserToDayHistoryOnline.Text;
        search = " select distinct FKOnlineuserUserId,OnlineuserLoginIp from TOnlineUser where OnlineuserType=2 and UserOnlineState = 1";
        lbl_OnlineLearnerCount.Text = obj.Count(search).ToString();

        //lbl_UserToDaCurrentyOnline.Text = opUser.QueryCurrentOnlineUser().ToString();
        //search = string.Format("convert(varchar(12),OnlineuserLoginTime,112) = '{0}'", DateTime.Now.ToString("yyyyMMdd"));
        //lbl_UserToDayOnline.Text = opUser.QueryOnlineUserCount(search).ToString();
        //search = string.Format("convert(varchar(12),OnlineuserLoginTime,112) > '{0}' and convert(varchar(12),OnlineuserLoginTime,112) < '{1}'", DateTime.Now.AddDays(0 - theDayNumOfWeek).ToString("yyyyMMdd"), DateTime.Now.AddDays(8 - theDayNumOfWeek).ToString("yyyyMMdd"));
        //lbl_UserToDayWeekOnline.Text = opUser.QueryOnlineUserCount(search).ToString();
    }
    public void rptClickCourse()//课程观看排行
    {
        string search = "";
        string orderBy = "Used desc";
        DataTable dt = opCourse.QueryCourse(search, orderBy, 10, 1);
        DataTable dt1 = new DataTable();
        dt.Columns.Add("CilckNum");
        string sql = "";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sql = "select sum(ResourceClickNum) as sums from TResource where ResourceID in (select FKCoursersResourceID from TCourseResource where FKCourseresCourseID=" + dt.Rows[i]["Course_ID"] + ")";
            dt1 = vq.Query(sql);
            if (dt1.Rows.Count > 0)
                dt.Rows[i]["CilckNum"] = dt1.Rows[0]["sums"].ToString();
            else
                dt.Rows[i]["CilckNum"] = "0";
            if (dt.Rows[i]["CilckNum"].ToString().Length == 0)
                dt.Rows[i]["CilckNum"] = "0";
        }
        rptClkCourse.DataSource = dt;
        rptClkCourse.DataBind();

    }


    protected void btn_Login_Click(object sender, EventArgs e)
    {
        //登录
        //登录信息
        PowerCreator.LMS.Web.DL.User.LoginInfo info = new PowerCreator.LMS.Web.DL.User.LoginInfo();

        PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();

        if (!CheckPage()) return;

        info.LoginIp = PowerCreator.LMS.Common.Utils.IPUtils.GetIP;
        info.LoginTime = DateTime.Now;
        info.UserName = txt_UserName.Text;
        info.UserPwd = txt_UserPwd.Text;
        string UserLocation = GetUserLocation();
        
        if (opUser.Login(info, ref login, ConfigurationManager.AppSettings["CheckLoginIP"].ToString(), UserLocation))
        {
            Session.Add(PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO, login);
            //opUser.UpdateOnlineUserList();
            //login.VOOnlineUser = opUser.AddOnlineUser(info, login.VOUser.UserId);
            PowerCreator.LMS.Common.Script.Script.ReloadMe();

            //btn_Login.Visible = false;
            //btn_LoginOut.Visible = true;

        }
        else
        {
            opUser.AddOnlineUser(info, PowerCreator.LMS.Web.User.User.LoginNoUserID);
            string msg = config.GetLanagerValueByKey(login.LoginMessage, PowerCreator.LMS.Language.LanagetItemType.MSG);

            PowerCreator.LMS.Common.Script.Script.Alert(this.Page, "al", msg);
        }
    }

    private bool CheckPage()
    {
        if (string.IsNullOrEmpty(txt_code.Text))
        {

            PowerCreator.LMS.Common.Script.Script.Alert(this.Page, "msg", "请输入正确的五位验证码！");
            return false;
        }
        if (Session["CheckCode"] != null)
        {
            string s = Session["CheckCode"].ToString();
            if (s.ToLower() != txt_code.Text.ToLower())
            {
                //lblLoginMsg.Text = config.GetLanagerValueByKey("Login_msg_code2", PowerCreator.LMS.Language.LanagetItemType.Page);
                PowerCreator.LMS.Common.Script.Script.Alert(this.Page, "msg", "请输入正确的五位验证码！");
                txt_code.Text = "";
                //Page.ClientScript.RegisterStartupScript(Page.GetType(), "showmy1", "<script>AutoColseAler()</script>");
                return false;
            }
        }
        if (string.IsNullOrEmpty(txt_UserName.Text))
        {

            PowerCreator.LMS.Common.Script.Script.Alert(this.Page, "msg", "请输入正确的帐户！");
            return false;
        }
        if (string.IsNullOrEmpty(txt_UserPwd.Text))
        {

            PowerCreator.LMS.Common.Script.Script.Alert(this.Page, "msg", "请输入正确的密码！");
            return false;
        }
        return true;

    }

    public string GetUserLocation()
    {
        try
        {
            WebClient webGetting = new WebClient();
            string userIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            string ipQueryResult = webGetting.DownloadString("http://www.ip.cn/getip.php?action=queryip&ip_url=" + userIP);
            string startString = @"来自：";
            int startIndex = ipQueryResult.LastIndexOf(startString) + startString.Length;
            int endIndex = ipQueryResult.LastIndexOf(@" ", startIndex);
            return ipQueryResult.Substring(startIndex, ipQueryResult.Length - startIndex);
        }
        catch
        {
            return string.Empty;
        }
    }

    protected void btn_LoginOut_Click(object sender, EventArgs e)
    {
        PowerCreator.LMS.Web.User.User opUser = new PowerCreator.LMS.Web.User.User();
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] != null)
        {
            login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            if (login != null)
                opUser.UpdateOnlineUserByUserID(login.VOLearner.Learner_Id, 2);
        }

        Session.Abandon();
        PowerCreator.LMS.Common.Script.Script.ReloadMe();
    }
}
